package com.itheima.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.authc.Authenticator;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authc.pam.AllSuccessfulStrategy;
import org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Shiro的配置类
 *
 * @author lenovo
 */
@Configuration
public class ShiroConfig {
    // shiro使用注解（@RequiresPermissions等）不无效及异常处理
    // 下面3个方法对注解权限起作用有很大的关系，请把下面3个方法，放在配置的最上面
    @Bean(name = "lifecycleBeanPostProcessor")
    public LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
        //Shiro生命周期处理器
        return new LifecycleBeanPostProcessor();
    }

    /**
     * 开启Shiro的注解(如@RequiresRoles,@RequiresPermissions),
     * 需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证
     */
    @Bean
    @DependsOn("lifecycleBeanPostProcessor")
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator creator = new DefaultAdvisorAutoProxyCreator();
        creator.setProxyTargetClass(true);
        return creator;
    }

    /**
     * 开启shiro aop注解支持.
     * 使用代理方式;所以需要开启代码支持;
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(@Qualifier("securityManager") SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

    /**
     * 创建ShiroFilterFactoryBean
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        //添加Shiro内置过滤器
        /**
         * Shiro内置过滤器，可以实现权限相关的拦截器
         *    常用的过滤器：
         *       anon: 无需认证（登录）可以访问
         *       authc: 必须认证才可以访问
         *       user: 如果使用rememberMe的功能可以直接访问
         *       perms： 该资源必须得到资源权限才可以访问
         *       role: 该资源必须得到角色权限才可以访问
         */
        Map<String, String> filterMap = new LinkedHashMap<String, String>();
		/*filterMap.put("/add", "authc");
		filterMap.put("/update", "authc");*/

        filterMap.put("/testThymeleaf", "anon");
        //放行login.html页面
        filterMap.put("/login", "anon");

        filterMap.put("/logout", "logout");

        //授权过滤器
        //注意：当前授权拦截后，shiro会自动跳转到未授权页面
        filterMap.put("/add", "perms[user:add]");
        filterMap.put("/update", "perms[user:update]");

        //角色过滤器
        filterMap.put("/admin", "roles[admin]");
        filterMap.put("/user", "roles[user]");

        filterMap.put("/*", "authc"); //URL权限采取第一次匹配优先的方式，这个应该放到最后

        //修改调整的登录页面
        shiroFilterFactoryBean.setLoginUrl("/toLogin");
        //设置未授权提示页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/noAuth");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);


        return shiroFilterFactoryBean;
    }

    /**
     * 创建DefaultWebSecurityManager
     */
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm,
                                                                  @Qualifier("secondRealm") SecondRealm secondRealm,
                                                                  @Qualifier("authenticator") Authenticator authenticator) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联realm
//        securityManager.setRealm(userRealm); //单个realm
//        securityManager.setRealm(secondRealm); //单个realm

        List<Realm> list = new ArrayList();
        list.add(userRealm); //第一个
        list.add(secondRealm);//第二个
        securityManager.setRealms(list);

//        securityManager.setAuthenticator(authenticator);//多个realm

//        securityManager.setCacheManager(cacheManager); //开启缓存

        return securityManager;
    }


    /**
     * 创建第1个Realm
     */
    @Bean(name = "userRealm")
    public UserRealm getUserRealm(@Qualifier("credentialsMatcher") CredentialsMatcher credentialsMatcher) {
        UserRealm userRealm = new UserRealm();
        userRealm.setCredentialsMatcher(credentialsMatcher);
        return userRealm;
    }

    /**
     * 创建第2个Realm
     */
    @Bean(name = "secondRealm")
    public SecondRealm getSecondRealm() {
        return new SecondRealm();
    }

    /**
     * 配置ShiroDialect，用于thymeleaf和shiro标签配合使用
     */
    @Bean
    public ShiroDialect getShiroDialect() {
        return new ShiroDialect();
    }


    /**
     * 认证器，可以实现多Realm认证，并且可以指定realm 认证策略
     */
    @Bean("authenticator")
    public ModularRealmAuthenticator getModularRealmAuthenticator(@Qualifier("userRealm") UserRealm userRealm,
                                                                  @Qualifier("secondRealm") SecondRealm secondRealm) {

        ModularRealmAuthenticator authenticator = new ModularRealmAuthenticator();

        /**
         * realm 认证策略
         * AtLeastOneSuccessfulStrategy 至少有一个Realm验证成功就登录成功（默认策略）
         * AllSuccessfulStrategy 全部的Realm验证必须都成功，才登录成功
         * FirstSuccessfulStrategy 第一个Realm验证成功就登录成功
         */
        authenticator.setAuthenticationStrategy(new AllSuccessfulStrategy()); //必须要在 setRealms()之前设置

        //添加多个Realm
        List<Realm> list = new ArrayList();
        list.add(userRealm); //第一个
        list.add(secondRealm);//第二个
        authenticator.setRealms(list);

        return authenticator;
    }


    /**
     * 密码比较器
     */
    @Bean("credentialsMatcher")
    public CredentialsMatcher credentialsMatcher() {
        //return new HashedCredentialsMatcher("MD5");
        return new CustomizedCredentialsMatcher();
    }


    @Bean
    public Map<String, String> buildFilterChainDefinitionMap() {
        Map<String, String> filterMap = new LinkedHashMap<>();

        filterMap.put("/testThymeleaf", "anon");
        //放行login.html页面
        filterMap.put("/login", "anon");

        filterMap.put("/logout", "logout");

        //授权过滤器
        //注意：当前授权拦截后，shiro会自动跳转到未授权页面
        filterMap.put("/add", "perms[user:add]");
        filterMap.put("/update", "perms[user:update]");

        //角色过滤器
        filterMap.put("/admin", "roles[admin]");
        filterMap.put("/user", "roles[user]");

        filterMap.put("/*", "authc"); //URL权限采取第一次匹配优先的方式，这个应该放到最后

        return filterMap;
    }

}
